package com.barradata.app0624.modules.contact

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.ContactsContract
import android.view.View
import android.widget.TextView
import com.barradata.BuildConfig
import com.barradata.R
import com.barradata.app0624.api.ApiService
import com.barradata.app0624.modules.web.EventType
import com.barradata.app0624.modules.web.WebCallbackEvent
import com.barradata.common.base.BaseActivity
import com.barradata.common.rxbinding.clickV
import com.barradata.common.rxbus.RxBus
import com.barradata.common.utils.ToastUtils
import com.barradata.common.view.AlertDialogFragment
import com.barradata.common.view.PlainTextPopupFragment
import com.example.hfiveandaplication.bean.ContactItemInfoData
import com.example.hfiveandaplication.bean.DictionaryItemData
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.Observable
import kotlinx.android.synthetic.main.contact_activity.*

/**
 * Author:    WuNan
 * Email:     wunan@barradata.com
 * Created:   2019/7/7 16:52
 * Description：  {@link com.barradata.app0624.modules.contact.ContactActivity2}
 **/
@Deprecated("即将废弃，请使用 RecyclerView 版本的实现")
class ContactActivity : BaseActivity() {
    companion object {
        fun actionStart(context: Context) {
            context.startActivity(Intent(context, ContactActivity::class.java))
        }

        private const val REQUEST_FOR_CONTACT_1 = 1
        private const val REQUEST_FOR_CONTACT_2 = 2
        private const val REQUEST_FOR_CONTACT_3 = 3
        private const val REQUEST_PERMISSION = Manifest.permission.READ_CONTACTS
    }

    private val rxPermissions = RxPermissions(this)

    private var contactRelationList: List<DictionaryItemData>? = null


    override fun getLayoutId() = R.layout.contact_activity

    override fun initView() {
        setupActionBar(toolbar)
        requestPermission()
        setupContactsTitle()
        setupContactsButtons()
        setupRelationButtons()
        setupNextButton()
    }

    @SuppressLint("SetTextI18n")
    private fun setupContactsTitle() {
        contact_title1.text = contact_title1.text.toString() + "1"
        contact_title2.text = contact_title2.text.toString() + "2"
        contact_title3.text = contact_title3.text.toString() + "3"
    }

    private fun checkData(): Boolean {
        if (contact_name_et1.text.isNullOrEmpty() ||
                contact_phone_button1.text.isNullOrEmpty() ||
                relation_button1.text.isNullOrEmpty() ||
                contact_name_et2.text.isNullOrEmpty() ||
                contact_phone_button2.text.isNullOrEmpty() ||
                relation_button2.text.isNullOrEmpty() ||
                contact_name_et3.text.isNullOrEmpty() ||
                contact_phone_button3.text.isNullOrEmpty() ||
                relation_button3.text.isNullOrEmpty()) {
            ToastUtils.showShort(R.string.auth_error_contact)
            return false;
        }
        val contractPhoneSet = HashSet<String>()
        contractPhoneSet.add(contact_phone_button1.text.toString())
        contractPhoneSet.add(contact_phone_button2.text.toString())
        contractPhoneSet.add(contact_phone_button3.text.toString())
        if (contractPhoneSet.size < 3) {
            ToastUtils.showShort(R.string.contact_auth_contact_repeat)
            return false;
        }
        return true;
    }


    private fun setupNextButton() {
        next_button.clickV().filter { checkData() }.subscribe {
            val info1 = ContactItemInfoData()
            info1.orderNo = "1"
            info1.mobile = contact_phone_button1.text.toString().trim()
            info1.userName = contact_name_et1.text.toString().trim()
            info1.relation = relation_button1.tag.toString().trim()
            info1.realtionValue = relation_button1.text.toString()
            val info2 = ContactItemInfoData()
            info2.orderNo = "2"
            info2.mobile = contact_phone_button2.text.toString().trim()
            info2.userName = contact_name_et2.text.toString().trim()
            info2.relation = relation_button2.tag.toString().trim()
            info2.realtionValue = relation_button2.text.toString()
            val info3 = ContactItemInfoData()
            info3.orderNo = "3"
            info3.mobile = contact_phone_button3.text.toString().trim()
            info3.userName = contact_name_et3.text.toString().trim()
            info3.relation = relation_button3.tag.toString().trim()
            info3.realtionValue = relation_button3.text.toString()
            ApiService.uploadContactInfo(listOf(info1, info2, info3))
                    .doOnComplete { showLoadingView() }
                    .doFinally { dismissLoadingView() }
                    .subscribe({
                        if (it.status == 200) {
                            RxBus.post(WebCallbackEvent(EventType.FROM_CONTACT))
                            finish()
                        } else {
                            ToastUtils.showShort(it.message)
                        }
                    }, {
                        ToastUtils.showShort(R.string.network_error)
                    })
        }.autoClean()
    }

    private fun setupRelationButtons() {
        Observable.fromArray(relation_button1, relation_button2, relation_button3)
                .map { it.clickV() }
                .flatMap { it }
                .subscribe { fetchDicData(it) }
                .autoClean()
    }

    private fun fetchDicData(view: View) {
        if (contactRelationList == null) {
            ApiService.getDictionary(ApiService.DictionaryType.COMMON_RELATION)
                    .doOnSubscribe { showLoadingView() }
                    .doFinally { dismissLoadingView() }
                    .subscribe({
                        contactRelationList = it.data
                        showDicFragment(view)
                    }, {
                        ToastUtils.showShort(R.string.network_error)
                    }).autoClean()
        } else {
            showDicFragment(view)
        }
    }

    private fun showDicFragment(view: View) {
        PlainTextPopupFragment(contactRelationList!!.map { it.dictValue }).apply {
            callbackAction = {
                (view as TextView).text = contactRelationList!![it].dictValue
                view.tag = contactRelationList!![it].dictCode
            }
        }.show(this)
    }

    private fun setupContactsButtons() {
        Observable.fromArray(contact_phone_button1, contact_phone_button2, contact_phone_button3)
                .map { it.clickV() }
                .flatMap { it }
                .filter { checkPermission() }
                .subscribe {
                    var requestCode = 0
                    when (it) {
                        contact_phone_button1 -> {
                            requestCode = REQUEST_FOR_CONTACT_1
                        }
                        contact_phone_button2 -> {
                            requestCode = REQUEST_FOR_CONTACT_2
                        }
                        contact_phone_button3 -> {
                            requestCode = REQUEST_FOR_CONTACT_3
                        }
                    }
                    go2Contacts(requestCode)
                }.autoClean()
    }

    private fun go2Contacts(requestCode: Int) {
        val intent = Intent(Intent.ACTION_PICK)
        intent.setDataAndType(ContactsContract.CommonDataKinds.Phone.CONTENT_URI
                , ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE)
        startActivityForResult(intent, requestCode)
    }

    private fun checkPermission(): Boolean {
        if (rxPermissions.isGranted(REQUEST_PERMISSION)) {
            return true
        } else {
            requestPermission()
            return false
        }
    }

    private fun requestPermission() {
        rxPermissions.requestEach(REQUEST_PERMISSION).subscribe {
            if (it.granted) {
                return@subscribe
            }
            val singleButtonAction: () -> Unit?
            if (it.shouldShowRequestPermissionRationale) {
                singleButtonAction = { requestPermission() }
            } else {
                singleButtonAction = { go2Setting() }
            }
            ToastUtils.showShort(R.string.get_permission_failure_hint)
            AlertDialogFragment.create(singleButtonAction).setCancelAble(false)
                    .setTitle(getString(R.string.get_permission_failure_hint))
                    .show(this)
        }.autoClean()
    }

    private fun go2Setting() {
        val localIntent = Intent()
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        localIntent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
        localIntent.data = Uri.fromParts("package", BuildConfig.APPLICATION_ID, null)
        startActivity(localIntent)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null || data.data == null) {
            return
        }
        val contactInfo = resolveContactCursor(data.data!!)
        val contactName = contactInfo[0]
        val contactPhoneNumber = contactInfo[1]
        when (requestCode) {
            REQUEST_FOR_CONTACT_1 -> {
                if (contactPhoneNumber == contact_phone_button2.text.toString() ||
                        contactPhoneNumber == contact_phone_button3.text.toString()) {
                    ToastUtils.showShort(R.string.contact_auth_contact_repeat)
                    return
                }
                contact_name_et1.setText(contactName)
                contact_phone_button1.text = contactPhoneNumber
            }
            REQUEST_FOR_CONTACT_2 -> {
                if (contactPhoneNumber == contact_phone_button1.text.toString() ||
                        contactPhoneNumber == contact_phone_button3.text.toString()) {
                    ToastUtils.showShort(R.string.contact_auth_contact_repeat)
                    return
                }
                contact_name_et2.setText(contactName)
                contact_phone_button2.text = contactPhoneNumber
            }
            REQUEST_FOR_CONTACT_3 -> {
                if (contactPhoneNumber == contact_phone_button1.text.toString() ||
                        contactPhoneNumber == contact_phone_button2.text.toString()) {
                    ToastUtils.showShort(R.string.contact_auth_contact_repeat)
                    return
                }
                contact_name_et3.setText(contactName)
                contact_phone_button3.text = contactPhoneNumber
            }
        }
    }

    private fun resolveContactCursor(data: Uri): Array<String?> {
        val cursor = contentResolver.query(data,
                arrayOf(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
                        , ContactsContract.CommonDataKinds.Phone.NUMBER),
                null, null, null)
        cursor?.moveToFirst()
        val contactName = cursor?.getString(0)
        val phoneNumber = cursor?.getString(1)
        logD(contactName.orEmpty() + phoneNumber.orEmpty())
        cursor?.close()
        return arrayOf(contactName, phoneNumber)
    }
}